<template>
  <div  style="padding: 15px;">
    <vxe-toolbar id="warehouseRecordId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>

      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
       :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="入驻商" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.shipmentName" clearable filterable placeholder="请选择入驻商">
            <el-option
              v-for="item in options"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="仓库" min-width="200" />
        <template v-slot:header="{ column }">
           <el-select v-model="listQuery.warehouseCode" filterable clearable placeholder="请选择仓库">
            <el-option
              v-for="item in warehousesArr"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <!-- <warehouseSelect @setWarehouseCode="setWarehouseCode" /> -->
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseSpaceName" title="库区" min-width="150" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseSpaceCode" clearable filterable placeholder="请选择库区">
            <el-option
              v-for="item in spacesArr"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
          <!-- <spaceSelect ref="spaceSelect" @setSpaceCode="setSpaceCode"/> -->
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="locationName" title="库位" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.locationName" placeholder="请输入库位名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodsName" title="商品名称" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodsName" placeholder="请输入商品名称" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodCode" title="商品编码" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.goodCode" placeholder="请输入商品编码" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="spec" title="规格" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.spec" placeholder="请输入规格" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="typeName" title="作业类型" min-width="150" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.type" placeholder="请输入作业类型 " style="width:100%" clearable>
            <el-option
              v-for="item in typeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="sourceCode" title="关联单号" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.sourceCode" placeholder="请输入关联单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="unitName" title="单位" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.unitName" placeholder="请输入单位" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="num" title="数量" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.numStart" placeholder="下限" type='number' style="width:45%;" />
          -
          <el-input v-model="listQuery.numEnd" placeholder="上限" type='number' style="width:45%;" />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="expirationQuantity" title="保质期（天）" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.expirationQuantityStart" placeholder="下限" type='number' style="width:45%;" />
          -
          <el-input v-model="listQuery.expirationQuantityEnd" placeholder="上限" type='number' style="width:45%;" />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtManufacture"
          show-header-overflow
          show-overflow
          title="生产日期"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtManufactureRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtManufacture')"
          />

        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtExpire"
          show-header-overflow
          show-overflow
          title="过期日期"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtExpireRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtExpire')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtStock"
          show-header-overflow
          show-overflow
          title="存货日期"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtStockRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtStock')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="receiveLot" title="收货批次" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.receiveLot" placeholder="请输入收货批次" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="isLock" title=锁定状态 min-width="150" sortable :formatter="formatterIsLock" />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.isLock" placeholder="请选择锁定状态 " style="width:100%" clearable>
            <el-option
              v-for="item in isLockData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          show-header-overflow
          show-overflow
          title="操作时间"
          min-width="400"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="createdName" title="操作人" min-width="150" sortable />
        <template #header>
          <el-input v-model="listQuery.createdName" placeholder="请输入操作人" clearable />
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import request from "@/utils/request";
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import { inventoryRecordList } from '@/api/basicInfo'
import { shipments } from '@/api/outStorage'
import warehouseSelect from '@/views/components/warehouseQuery/warehouseSelect'
import spaceSelect from '@/views/components/warehouseQuery/spaceSelect'
import locationSelect from '@/views/components/warehouseQuery/locationSelect'
export default {
  name: '库存日志',
  components: {
    warehouseSelect,
    spaceSelect,
    locationSelect,
  },
  data() {
    return {
      message: '',
      state:'',
      warehouseData: [],
      spaceData: [],
      locationData: [],
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      loading: false,
      allAlign: 'center',
      tableData: [],
      gmtCreatedRange: "",
      gmtExpireRange: "",
      gmtAuthRange: "",
      gmtManufactureRange: "",
      gmtStockRange: "",
      copy: false,
      // 锁定状态
      isLockData:[
          { code: "0", name: "否" },
          { code: "1",name: "是" },
      ],
      // 类型
      typeList: [
        { code: "receive", name: "收货"},
        { code: "inbound", name: "入库"},
        { code: "pick", name: "拣货"},
        { code: "outbound", name: "出库"},
        { code: "move", name: "移位"},

      ],
      listQuery: {
        warehouseCode: '',
        total: 0,             //总数
        createdBy:'',         //创建人
        createdByName:'',         //创建人
        modifiedBy:'',        //修改人
        modifiedByName:'',        //修改人
        gmtCreated:'',        //创建时间
        gmtModified:'',       //修改时间
        numStart: null,
        numEnd: null,
        expirationQuantityStart: '',
        expirationQuantityEnd: '',
        code:'',                      //数据标识 ,
        name:'',                      //名称 ,
        remarks:'',                   //备注 ,
        shipmentCode:'',              //所属入驻商 ,
        status:'',                    //状态 ,
        statusText:'',                    //状态描述 ,
        shipmentName:'',                    //入驻商名称 ,
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
      },
      warehousesArr:[],
      spacesArr:[],
      locationsArr:[],
      states:this.$store.state.user,
      options: []
    }
  },
  created() {
    this.findList()
    this.query()

  },
  methods: {
    querySearchAsync(queryString, cb) {
      request({
        url: '/wms/location/getDistinctLocation',
        method: 'get',
        params: { serialNumber: queryString,warehouseCode:this.states.authorizeDataCode }
      }).then(response => {
        let arr = response.data.map(v=>{
          return {...v,value:v.serialNumber}
        })
        let results = queryString ? arr.filter(this.createStateFilter(queryString)) : arr;
        clearTimeout(this.timeout);
         this.timeout = setTimeout(() => {
          cb(results);
        }, 1000);
      })
    },
    createStateFilter(queryString){
      return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
    },
    handleSelect(item) {
      this.listQuery.location = item.code
    },
    query(){
      //仓库
      request({
        url: '/wms/warehouse/chooseData',
        method: 'get',
        params: { warehouseName:''}
      }).then(response => {
        this.warehousesArr = response.data
      })
      //库区
      request({
        url: '/wms/warehouseSpace/chooseAllData',
        method: 'get',
        params: { warehouseCode: '' }
      }).then(response => {
        this.spacesArr = response.data
      })
      // //库位
      // request({
      //   url: '/wms/location/chooseAllData',
      //   method: 'get',
      //   params: { spaceCode: '' }
      // }).then(response => {
      //   this.selectLoading = false
      //   this.locationsArr = response.data
      // })
    },
    //获取列表
    findList() {
      this.loading = true
      shipments().then(res => {
        this.options = res.data
      })
      return inventoryRecordList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.listQuery.total = response.data.total
        this.loading = false
      })
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },

    // 时间
    changeDate(value, prefix) {
        if (value) {
          this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
          this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
        } else {
          this.listQuery[`${prefix}Start`] = "";
          this.listQuery[`${prefix}End`] = "";
        }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 底部颜色设置
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    },

    formatterIsLock({cellValue}){
      if(cellValue == 0){
        return "否"
      }else{
        return "是"
      }
    },

    // setWarehouseCode(val){
    //   this.listQuery.warehouseCode = val;
    //   this.listQuery.warehouseSpaceCode = '';
    //   this.$nextTick(function () {
    //     this.$refs.spaceSelect.findList(val);
    //   })
    // },

    // setSpaceCode(val){
    //   this.listQuery.warehouseSpaceCode = val;
    //   this.listQuery.location = '';
    //   this.$nextTick(function () {
    //     this.$refs.locationSelect.findList(val);
    //   })
    // },

    // setLocationCode(val){
    //   this.listQuery.location = val;
    // },
  }
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
